package lockAndCondition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class BoundedBuffer {
	final public Lock lock=new ReentrantLock();
	Object[] buffer=new Object[100];
	public int putptr,takeptr,count;
	
	Condition fullCondition=lock.newCondition();
	Condition emptyCondition=lock.newCondition();
	
	public void put(Object object) throws InterruptedException{
		lock.lock();
		try {
			while(count==buffer.length){
				fullCondition.await();
			}
			buffer[putptr]=object;
			if(++putptr==buffer.length){
				putptr=0;
			}
			count++;
			emptyCondition.signal();
		} finally  {
			// TODO Auto-generated catch block
			lock.unlock();
		}
		
	}
	
	public Object take() throws InterruptedException{
		lock.lock();
		Object object;
		try {
			while(count==0){
				emptyCondition.await();
			}
			object = buffer[takeptr];
			if(++takeptr==buffer.length){
				takeptr=0;
			}
			count--;
			fullCondition.notify();
		} finally  {
			// TODO Auto-generated catch block
			lock.unlock();
		}
		return object;
	}
	
}
